﻿using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Text;
using adb;
using Microsoft.EntityFrameworkCore;
using Masuit.Tools;
using System.Threading.Tasks;

namespace SensorCollection
{
    /// <summary>
    /// 停机流程信号
    /// </summary>
    public class SignalStop : IDataDealwith
    {
        private MqttServer mqttServer;
        private DbContextOptionsBuilder<DeviceDbContext> optionsBuilder = new DbContextOptionsBuilder<DeviceDbContext>();

        public DbContextOptionsBuilder<MyDbContext> MyOptionsBuilder { get; }

        public SignalStop(MqttServer mqttServer, DbContextOptionsBuilder<DeviceDbContext> optionsBuilde, DbContextOptionsBuilder<MyDbContext> MyOptionsBuilder)
        {
            this.mqttServer = mqttServer;
            this.optionsBuilder = optionsBuilde;
            this.MyOptionsBuilder = MyOptionsBuilder;
        }

        public long keyId => 820092;


        public object JsonToModel(string json, string deviceSN = null)
        {
            return System.Text.Json.JsonSerializer.Deserialize< Dictionary< string,decimal>>(json);
        }
        public async Task ReactData(object obj, string Topic, string deviceSN = null)
        {
            try
            {
                Dictionary<string, decimal> obj1 = obj as Dictionary<string, decimal>;
                if (obj1 == null) return;
                if (Topic.IsNullOrEmpty()) return;
                if ("wsr".Equals(deviceSN))
                {
                    tSignalStop_WSR ssd = new tSignalStop_WSR();
                    ssd.Topic = Topic;
                    ssd.addTime = DateTime.Now;
                    Type t = typeof(tSignalStop_WSR);
                    foreach (var item in obj1)
                    {
                        t.GetProperty(item.Key)?.SetValue(ssd, item.Value);
                    }
                    using (var db = new DeviceDbContext(this.optionsBuilder.Options))
                    {
                        await db.tSignalStop_WSR.AddAsync(ssd);
                        await db.SaveChangesAsync();
                    }
                }
                else
                {
                    tSignalStop ssd = new tSignalStop();
                    ssd.Topic = Topic;
                    ssd.addTime = DateTime.Now;
                    Type t = typeof(tSignalStop);
                    foreach (var item in obj1)
                    {
                        t.GetProperty(item.Key)?.SetValue(ssd, item.Value);
                    }
                    using (var db = new DeviceDbContext(this.optionsBuilder.Options))
                    {
                        await db.tSignalStop.AddAsync(ssd);
                        await db.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex) {
                Console.WriteLine("tSignalStop:" + ex.Message);
            }
        }

    }
}
